/*
 * 数据插入
 */
package io.github.ilkgunel.operations;

import io.github.ilkgunel.database.AccessMongoDB;
import org.bson.Document;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * @author ilkaygunel
 */
@WebServlet(name = "test3_2", urlPatterns = {"/test3_2"})
public class test3_2 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        String insertMessage = "";

        String tid= request.getParameter("tid");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        int age = Integer.parseInt(request.getParameter("age"));
        String birthday = request.getParameter("birthday");
        String dname= request.getParameter("dname");
        String theclass= request.getParameter("class");

        AccessMongoDB accessMongoDB = new AccessMongoDB();

        try {
            accessMongoDB.getCollection("teacher").insertOne(
                    new Document()
                    .append("tid",tid )
                    .append("name", name)
                    .append("sex", sex)
                    .append("age",age)

                    .append("dname",dname)

            );
            insertMessage = "插入成功！！!";
            System.out.println(insertMessage);
        } catch (Exception e) {
            insertMessage = "An error occured while inserting data! Error is:"+e;
            System.out.println(insertMessage);
        }
        request.setAttribute("insertMessage", insertMessage);
        int index=request.getHeader("Referer").indexOf("test");
        RequestDispatcher dispatcher = request.getRequestDispatcher(request.getHeader("Referer").substring(index));
        dispatcher.forward(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String insertMessage = "";
        request.setAttribute("insertMessage", insertMessage);
        int index=request.getHeader("Referer").indexOf("test");
        RequestDispatcher dispatcher = request.getRequestDispatcher(request.getHeader("Referer").substring(index));
        dispatcher.forward(request, response);
    }
}
